<template>
  <div class="invite-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1 class="page-title">邀请中心</h1>
    </div>

    <div class="invite-content">
      <!-- 邀请管理内容 -->
      <div class="tab-content">
        <!-- 邀请统计卡片 -->
        <div class="stats-section">
          <a-skeleton :loading="statsLoading" active>
            <div class="stats-card">
              <div class="stat-item" @click="showStatDetail('totalInvitees')">
                <div class="stat-icon">👥</div>
                <div class="stat-content">
                  <div class="stat-number">{{ formatNumber(inviteStats.totalInvitees || 0) }}</div>
                  <div class="stat-label">邀请人数</div>
                  <div class="stat-trend" v-if="inviteStats.inviteGrowth">
                    <span v-if="inviteStats.inviteGrowth > 0">↗</span>
                    <span v-else>↘</span>
                    {{ Math.abs(inviteStats.inviteGrowth) }}%
                  </div>
                </div>
              </div>
              <div class="stat-item" @click="showStatDetail('totalCommission')">
                <div class="stat-icon">💰</div>
                <div class="stat-content">
                  <div class="stat-number">¥{{ formatMoney(inviteStats.totalCommission || 0) }}</div>
                  <div class="stat-label">累计佣金</div>
                  <div class="stat-trend" v-if="inviteStats.commissionGrowth">
                    <span v-if="inviteStats.commissionGrowth > 0">↗</span>
                    <span v-else>↘</span>
                    {{ Math.abs(inviteStats.commissionGrowth) }}%
                  </div>
                </div>
              </div>
              <div class="stat-item" @click="showStatDetail('sellCommission')">
                <div class="stat-icon">🏪</div>
                <div class="stat-content">
                  <div class="stat-number">¥{{ formatMoney(inviteStats.sellCommission || 0) }}</div>
                  <div class="stat-label">出售佣金</div>
                </div>
              </div>
              <div class="stat-item" @click="showStatDetail('rentCommission')">
                <div class="stat-icon">🎯</div>
                <div class="stat-content">
                  <div class="stat-number">¥{{ formatMoney(inviteStats.rentCommission || 0) }}</div>
                  <div class="stat-label">租赁佣金</div>
                </div>
              </div>
            </div>
          </a-skeleton>
        </div>

        <!-- 邀请码和邀请用户列表 - 左右对齐 -->
        <div class="invite-sections-container">
          <!-- 邀请码卡片 -->
          <div class="invite-code-section">
            <a-card title="我的邀请码" class="invite-card">
              <!-- <template #extra>
                <a-button type="link" @click="refreshInviteCode" :loading="refreshing">
                  刷新
                </a-button>
              </template> -->
              
              <!-- 无权限提示 -->
              <div v-if="permissionChecked && !canInvite" class="no-permission">
                <div class="permission-icon">🚫</div>
                <div class="permission-text">
                  <h3>暂无邀请权限</h3>
                  <p>您当前没有邀请码生成权限，请联系管理员开通后再试。</p>
                  <a-button type="primary" @click="contactAdmin">联系管理员</a-button>
                </div>
              </div>
              
              <!-- 有权限时显示正常内容 -->
              <div v-else class="invite-code-content">
                <a-skeleton :loading="codeLoading" active>
                  <div class="code-display" v-if="inviteCodeData">
                    <div class="code-text">{{ inviteCodeData.code }}</div>
                    <div class="code-usage">
                      已邀请 {{ inviteCodeData.usageCount || 0 }} 人
                      <!-- <a-tag color="blue" v-if="inviteCodeData.isActive">活跃</a-tag>
                      <a-tag color="red" v-else>已过期</a-tag> -->
                    </div>
                    <!-- <div class="code-expiry" v-if="inviteCodeData.expiryDate">
                      有效期至：{{ formatDate(inviteCodeData.expiryDate) }}
                    </div> -->
                  </div>
                  
                  <div class="code-actions">
                    <a-button 
                      type="primary" 
                      size="large"
                      @click="generateInviteCode" 
                      :loading="generating"
                      v-if="!inviteCodeData"
                      :disabled="!canInvite"
                    >
                      生成邀请码
                    </a-button>
                    
                    <div class="action-buttons" v-if="inviteCodeData">
                      <a-button @click="copyCode" :loading="copying">
                        复制邀请码
                      </a-button>
                      <a-button type="primary" @click="copyInviteLink" :loading="copying">
                        复制邀请链接
                      </a-button>
                      <!-- <a-button @click="shareInvite" v-if="canShare">
                        分享
                      </a-button> -->
                    </div>
                  </div>

                  <div class="invite-link" v-if="inviteCodeData">
                    <div class="link-header">
                      <span class="link-label">邀请链接：</span>
                      <!-- <a-button type="link" size="small" @click="toggleLinkDisplay">
                        {{ showFullLink ? '收起' : '展开' }}
                      </a-button> -->
                    </div>
                    <div class="link-text" :class="{ 'collapsed': !showFullLink }">
                      {{ inviteCodeData.inviteUrl }}
                    </div>
                  </div>
                </a-skeleton>
              </div>
            </a-card>
          </div>

          <!-- 邀请用户列表 -->
          <div class="invitees-section">
            <a-card title="我的邀请" class="invitees-card">
              <a-table 
                :columns="inviteesColumns" 
                :data-source="inviteesList" 
                :pagination="invitePagination"
                :loading="inviteLoading"
                @change="handleInviteTableChange"
                row-key="_id"
                :scroll="{ x: 800 }"
              >
                <template #bodyCell="{ column, record }">
                  <template v-if="column.dataIndex === 'invitee'">
                    <div class="user-info">
                      <!-- <a-avatar :src="record.invitee?.avatar" size="small">
                        {{ record.invitee?.username?.charAt(0) }}
                      </a-avatar> -->
                      <div class="user-details">
                        <div class="username">{{ record.invitee?.username }}</div>
                        <div class="phone">{{ formatPhone(record.invitee?.phone) }}</div>
                      </div>
                    </div>
                  </template>
                  
                  <template v-if="column.dataIndex === 'commission'">
                    <div class="commission-info">
                      <div class="amount">¥{{ formatMoney(record.commission?.total || 0) }}</div>
                      <div class="count">{{ record.commission?.count || 0 }}笔</div>
                    </div>
                  </template>
                  
                  <template v-if="column.dataIndex === 'registeredAt'">
                    <div class="date-info">
                      <div class="date">{{ formatDate(record.registeredAt) }}</div>
                      <div class="time-ago">{{ getTimeAgo(record.registeredAt) }}</div>
                    </div>
                  </template>

                  <template v-if="column.dataIndex === 'status'">
                    <a-tag :color="getInviteeStatusColor(record.status)">
                      {{ getInviteeStatusText(record.status) }}
                    </a-tag>
                  </template>

                  <!-- <template v-if="column.dataIndex === 'action'">
                    <a-space>
                      <a-button type="link" size="small" @click="viewInviteeDetail(record)">
                        查看详情
                      </a-button>
                      <a-button type="link" size="small" @click="sendMessage(record)">
                        发送消息
                      </a-button>
                    </a-space>
                  </template> -->
                </template>

                <template #emptyText>
                  <div class="empty-state">
                    <div class="empty-icon">📋</div>
                    <p>暂无邀请记录</p>
                    <a-button type="primary" @click="generateInviteCode">立即邀请</a-button>
                  </div>
                </template>
              </a-table>
            </a-card>
          </div>
        </div>

        <!-- 佣金明细 -->
        <div class="commission-history">
          <a-card title="佣金明细" class="history-card">
            <template #extra>
              <div class="filter-controls">
                <!-- <a-range-picker 
                  v-model:value="dateRange" 
                  @change="handleDateRangeChange"
                  style="margin-right: 16px;"
                  placeholder="['开始日期', '结束日期']"
                /> -->
                <a-select 
                  v-model:value="filterType" 
                  @change="handleFilterChange"
                  style="width: 120px; margin-right: 16px;"
                  placeholder="类型筛选"
                >
                  <a-select-option value="">全部</a-select-option>
                  <a-select-option value="sell">出售佣金</a-select-option>
                  <a-select-option value="rent">租赁佣金</a-select-option>
                </a-select>
                
                <a-select 
                  v-model:value="filterStatus" 
                  @change="handleFilterChange"
                  style="width: 120px; margin-right: 16px;"
                  placeholder="状态筛选"
                >
                  <a-select-option value="">全部状态</a-select-option>
                  <a-select-option value="pending">待发放</a-select-option>
                  <a-select-option value="paid">已发放</a-select-option>
                  <a-select-option value="cancelled">已取消</a-select-option>
                </a-select>
                
                <a-button @click="refreshCommissionData" :loading="commissionLoading">
                  刷新
                </a-button>
                
                <!-- <a-button @click="exportCommission" :loading="exporting">
                  导出
                </a-button> -->
              </div>
            </template>

            <a-table 
              :columns="commissionColumns" 
              :data-source="commissionList" 
              :pagination="commissionPagination"
              :loading="commissionLoading"
              @change="handleCommissionTableChange"
              row-key="_id"
              :scroll="{ x: 1200 }"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.dataIndex === 'type'">
                  <a-tag :color="record.type === 'sell' ? 'blue' : 'green'">
                    {{ record.type === 'sell' ? '出售佣金' : '租赁佣金' }}
                  </a-tag>
                </template>
                
                <template v-if="column.dataIndex === 'invitee'">
                  <div class="user-info">
                    <div class="user-details">
                      <div class="username">{{ record.invitee?.username }}</div>
                      <div class="phone">{{ formatPhone(record.invitee?.phone) }}</div>
                    </div>
                  </div>
                </template>
                
                <template v-if="column.dataIndex === 'account'">
                  <div class="account-info">
                    <span class="account-number">{{ record.account?.number }}</span>
                    <div class="account-type">{{ record.account?.type }}</div>
                  </div>
                </template>
                
                <template v-if="column.dataIndex === 'orderAmount'">
                  <span class="order-amount">¥{{ formatMoney(record.orderAmount || 0) }}</span>
                </template>
                
                <template v-if="column.dataIndex === 'commissionRate'">
                  <span class="commission-rate">{{ (record.commissionRate * 100).toFixed(1) }}%</span>
                </template>
                
                <template v-if="column.dataIndex === 'commissionAmount'">
                  <span class="commission-amount">¥{{ formatMoney(record.commissionAmount || 0) }}</span>
                </template>
                
                <template v-if="column.dataIndex === 'status'">
                  <a-tag :color="getStatusColor(record.status)">
                    {{ getStatusText(record.status) }}
                  </a-tag>
                </template>
                
                <template v-if="column.dataIndex === 'paidAt'">
                  <div class="date-info">
                    <div class="date">{{ record.paidAt ? formatDate(record.paidAt) : '-' }}</div>
                    <div class="time-ago" v-if="record.paidAt">{{ getTimeAgo(record.paidAt) }}</div>
                  </div>
                </template>

                <template v-if="column.dataIndex === 'remark'">
                  <a-tooltip :title="record.remark" v-if="record.remark">
                    <span class="remark">{{ record.remark }}</span>
                  </a-tooltip>
                  <span v-else>-</span>
                </template>
               
              </template>

              <template #emptyText>
                <div class="empty-state">
                  <div class="empty-icon">💰</div>
                  <p>暂无佣金记录</p>
                  <a-button type="primary" @click="generateInviteCode">立即邀请</a-button>
                </div>
              </template>
            </a-table>
          </a-card>
        </div>

        <!-- 佣金规则说明 -->
        <!-- <div class="commission-rules-section">
          <a-card title="佣金计算规则" class="rules-card">
            <div class="rules-content">
              <div class="rule-section" @click="showRuleDetail('sell')">
                <h4 class="rule-title">
                  <span class="rule-icon">🏪</span>
                  出售账号佣金
                </h4>
                <div class="rule-detail">
                  <div class="rule-formula">
                    佣金 = 平台利润 × {{ ((inviteStats.commissionRate?.sell || 0.3) * 100).toFixed(0) }}%
                  </div>
                  <div class="rule-desc">
                    当您邀请的用户出售账号成功后，系统会根据该笔交易的平台利润计算您的佣金。
                    平台利润 = 租客支付价格 - 出号主收入价格
                  </div>
                </div>
              </div>
              
              <div class="rule-section" @click="showRuleDetail('rent')">
                <h4 class="rule-title">
                  <span class="rule-icon">🎯</span>
                  租赁账号佣金
                </h4>
                <div class="rule-detail">
                  <div class="rule-formula">
                    佣金 = 订单金额 × {{ ((inviteStats.commissionRate?.rent || 0.05) * 100).toFixed(0) }}%
                  </div>
                  <div class="rule-desc">
                    当您邀请的用户租赁账号并完成支付后，系统会根据该笔订单的金额计算您的佣金。
                  </div>
                </div>
              </div>
              
              <div class="rule-section" @click="showRuleDetail('timing')">
                <h4 class="rule-title">
                  <span class="rule-icon">⚡</span>
                  发放时机
                </h4>
                <div class="rule-detail">
                  <ul class="rule-list">
                    <li>出售佣金：订单完成并确认后自动发放</li>
                    <li>租赁佣金：用户支付成功后自动发放</li>
                    <li>佣金直接发放到您的账户余额中，可随时提现</li>
                  </ul>
                </div>
              </div>
            </div>
          </a-card>
        </div> -->
      </div>
    </div>

    <!-- 统计详情弹窗 -->
    <a-modal
      v-model:open="statDetailVisible"
      :title="statDetailTitle"
      width="600px"
      :footer="null"
    >
      <div class="stat-detail-content">
        <div class="stat-chart">
          <!-- 这里可以添加图表组件 -->
          <div class="chart-placeholder">图表区域</div>
        </div>
        <div class="stat-summary">
          <div class="summary-item">
            <span class="label">当前值：</span>
            <span class="value">{{ statDetailData.current }}</span>
          </div>
          <div class="summary-item">
            <span class="label">增长率：</span>
            <span class="value" :class="{ 'positive': statDetailData.growth > 0, 'negative': statDetailData.growth < 0 }">
              {{ statDetailData.growth > 0 ? '+' : '' }}{{ statDetailData.growth }}%
            </span>
          </div>
        </div>
      </div>
    </a-modal>

    <!-- 佣金计算器弹窗 -->
    <a-modal
      v-model:open="calculatorVisible"
      title="佣金计算器"
      width="500px"
      :footer="null"
    >
      <div class="calculator-content">
        <a-form layout="vertical">
          <a-form-item label="计算类型">
            <a-radio-group v-model:value="calculatorType">
              <a-radio value="sell">出售佣金</a-radio>
              <a-radio value="rent">租赁佣金</a-radio>
            </a-radio-group>
          </a-form-item>
          
          <a-form-item label="订单金额" v-if="calculatorType === 'rent'">
            <a-input-number
              v-model:value="calculatorAmount"
              :min="0"
              :precision="2"
              style="width: 100%"
              placeholder="请输入订单金额"
            />
          </a-form-item>
          
          <a-form-item label="平台利润" v-if="calculatorType === 'sell'">
            <a-input-number
              v-model:value="calculatorProfit"
              :min="0"
              :precision="2"
              style="width: 100%"
              placeholder="请输入平台利润"
            />
          </a-form-item>
          
          <a-form-item label="预计佣金">
            <div class="commission-result">
              ¥{{ calculatedCommission }}
            </div>
          </a-form-item>
        </a-form>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch, onUnmounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { getInviteStats, getMyInviteCode, generateInviteCode as apiGenerateInviteCode, getMyInvitees, getCommissionHistory } from '~/api/invite.js'

// 响应式数据
const inviteStats = ref({})
const inviteCodeData = ref(null)
const inviteesList = ref([])
const inviteLoading = ref(false)
const generating = ref(false)
const canInvite = ref(true) // 用户是否有邀请权限
const permissionChecked = ref(false) // 是否已检查权限
const invitePagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
})

// 佣金相关数据
const commissionList = ref([])
const commissionLoading = ref(false)
const filterType = ref('')
const filterStatus = ref('') // 新增状态筛选
const commissionPagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
})

// 邀请用户表格列定义
const inviteesColumns = [
  {
    title: '被邀请用户',
    dataIndex: 'invitee',
    key: 'invitee',
    width: 150,
    fixed: 'left'
  },
  {
    title: '邀请码',
    dataIndex: 'inviteCode',
    key: 'inviteCode',
    width: 120
  },
  {
    title: '注册时间',
    dataIndex: 'registeredAt',
    key: 'registeredAt',
    width: 160,
    // sorter: true
  },
  // {
  //   title: '状态',
  //   dataIndex: 'status',
  //   key: 'status',
  //   width: 100
  // },
  // {
  //   title: '操作',
  //   dataIndex: 'action',
  //   key: 'action',
  //   width: 150,
  //   fixed: 'right'
  // }
]

// 佣金表格列定义
const commissionColumns = [
  {
    title: '类型',
    dataIndex: 'type',
    key: 'type',
    width: 100,
    filters: [
      { text: '出售佣金', value: 'sell' },
      { text: '租赁佣金', value: 'rent' }
    ]
  },
  {
    title: '被邀请用户',
    dataIndex: 'invitee',
    key: 'invitee',
    width: 150,
    fixed: 'left'
  },
  {
    title: '佣金金额',
    dataIndex: 'commissionAmount',
    key: 'commissionAmount',
    width: 120,
    sorter: true
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
    filters: [
      { text: '待发放', value: 'pending' },
      { text: '已发放', value: 'paid' },
      { text: '已取消', value: 'cancelled' }
    ]
  },
  {
    title: '发放时间',
    dataIndex: 'paidAt',
    key: 'paidAt',
    width: 150,
    sorter: true
  },
  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',
    width: 120
  },
]

// 骨架屏和加载状态
const statsLoading = ref(true)
const codeLoading = ref(true)
const refreshing = ref(false)
const copying = ref(false)
const exporting = ref(false)

// 邀请链接展开/收起
const showFullLink = ref(false)

// 统计详情弹窗
const statDetailVisible = ref(false)
const statDetailTitle = ref('')
const statDetailData = ref({})

// 佣金计算器弹窗
const calculatorVisible = ref(false)
const calculatorType = ref('sell')
const calculatorAmount = ref(0)
const calculatorProfit = ref(0)
const calculatedCommission = ref('0.00')

// 搜索文本
const inviteSearchText = ref('')

// 日期范围筛选
const dateRange = ref([])

// 数据缓存
const dataCache = ref({
  stats: null,
  inviteCode: null,
  invitees: new Map(),
  commission: new Map()
})

// 计算属性
const canShare = computed(() => {
  return navigator.share && inviteCodeData.value?.inviteUrl
})

const totalCommissionAmount = computed(() => {
  return commissionList.value.reduce((sum, item) => sum + (item.commissionAmount || 0), 0)
})

const pendingCommissionAmount = computed(() => {
  return commissionList.value
    .filter(item => item.status === 'pending')
    .reduce((sum, item) => sum + (item.commissionAmount || 0), 0)
})

// 处理权限错误
const handlePermissionError = (error) => {
  if (error.response && error.response.status === 403) {
    canInvite.value = false
    message.error(error.response.data.message || '您暂无邀请权限，请联系管理员开通')
    return true
  }
  return false
}

// 获取邀请统计
const fetchInviteStats = async () => {
  try {
    statsLoading.value = true
    
    // 检查缓存
    const cacheKey = 'stats'
    if (dataCache.value.stats && Date.now() - dataCache.value.stats.timestamp < 5 * 60 * 1000) {
      inviteStats.value = dataCache.value.stats.data
      return
    }
    
    const response = await getInviteStats()
    if (response.status === 'success') {
      inviteStats.value = response.data
      // 更新缓存
      dataCache.value.stats = {
        data: response.data,
        timestamp: Date.now()
      }
    }
    permissionChecked.value = true
  } catch (error) {
    console.error('获取邀请统计失败:', error)
    permissionChecked.value = true
    if (!handlePermissionError(error)) {
      message.error('获取邀请统计失败')
    }
  } finally {
    statsLoading.value = false
  }
}

// 获取我的邀请码
const fetchMyInviteCode = async () => {
  try {
    codeLoading.value = true
    
    // 检查缓存
    if (dataCache.value.inviteCode && Date.now() - dataCache.value.inviteCode.timestamp < 2 * 60 * 1000) {
      inviteCodeData.value = dataCache.value.inviteCode.data
      return
    }
    
    const response = await getMyInviteCode()
    if (response.status === 'success') {
      inviteCodeData.value = response.data
      // 更新缓存
      dataCache.value.inviteCode = {
        data: response.data,
        timestamp: Date.now()
      }
    }
  } catch (error) {
    console.error('获取邀请码失败:', error)
    if (!handlePermissionError(error)) {
      message.error('获取邀请码失败')
    }
  } finally {
    codeLoading.value = false
  }
}

// 生成邀请码
const generateInviteCode = async () => {
  if (!canInvite.value) {
    message.error('您暂无邀请权限，请联系管理员开通')
    return
  }
  
  try {
    generating.value = true
    const response = await apiGenerateInviteCode()
    if (response.status === 'success') {
      inviteCodeData.value = response.data
      // 清除缓存
      dataCache.value.inviteCode = null
      message.success('邀请码生成成功!')
      
      // 刷新统计数据
      await fetchInviteStats()
    }
  } catch (error) {
    console.error('生成邀请码失败:', error)
    if (!handlePermissionError(error)) {
      message.error('生成邀请码失败')
    }
  } finally {
    generating.value = false
  }
}

// 刷新邀请码
const refreshInviteCode = async () => {
  refreshing.value = true
  // 清除缓存
  dataCache.value.inviteCode = null
  await fetchMyInviteCode()
  refreshing.value = false
}

// 获取邀请用户列表
const fetchInvitees = async (page = 1) => {
  try {
    inviteLoading.value = true
    
    // 检查缓存
    const cacheKey = `invitees_${page}_${inviteSearchText.value}`
    if (dataCache.value.invitees.has(cacheKey)) {
      const cached = dataCache.value.invitees.get(cacheKey)
      if (Date.now() - cached.timestamp < 2 * 60 * 1000) {
        inviteesList.value = cached.data.list
        invitePagination.value = {
          ...invitePagination.value,
          current: cached.data.pagination.current,
          total: cached.data.pagination.total
        }
        return
      }
    }
    
    const response = await getMyInvitees({
      page: page,
      limit: invitePagination.value.pageSize,
      search: inviteSearchText.value // 添加搜索参数
    })
    
    if (response.status === 'success') {
      inviteesList.value = response.data.list
      invitePagination.value = {
        ...invitePagination.value,
        current: response.data.pagination.current,
        total: response.data.pagination.total
      }
      
      // 更新缓存
      dataCache.value.invitees.set(cacheKey, {
        data: response.data,
        timestamp: Date.now()
      })
    }
  } catch (error) {
    console.error('获取邀请用户列表失败:', error)
    message.error('获取邀请用户列表失败')
  } finally {
    inviteLoading.value = false
  }
}

// 处理邀请用户搜索
const handleInviteSearch = () => {
  invitePagination.value.current = 1
  fetchInvitees(1)
}

// 导出邀请用户
const exportInvitees = async () => {
  exporting.value = true
  try {
    const response = await getMyInvitees({
      page: 1,
      limit: invitePagination.value.total,
      search: inviteSearchText.value
    })
    if (response.status === 'success') {
      const blob = new Blob([JSON.stringify(response.data.list, null, 2)], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `我的邀请用户_${new Date().toISOString().slice(0, 10)}.json`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
      message.success('邀请用户列表导出成功！')
    }
  } catch (error) {
    console.error('导出邀请用户失败:', error)
    message.error('导出邀请用户失败')
  } finally {
    exporting.value = false
  }
}

// 获取佣金历史
const fetchCommissionHistory = async (page = 1, pageSize = 10) => {
  try {
    commissionLoading.value = true
    
    // 检查缓存
    const cacheKey = `commission_${page}_${filterType.value}_${filterStatus.value}_${JSON.stringify(dateRange.value)}`
    if (dataCache.value.commission.has(cacheKey)) {
      const cached = dataCache.value.commission.get(cacheKey)
      if (Date.now() - cached.timestamp < 2 * 60 * 1000) {
        commissionList.value = cached.data.list
        commissionPagination.value = {
          ...commissionPagination.value,
          current: cached.data.pagination.current,
          total: cached.data.pagination.total,
          pageSize: cached.data.pagination.pageSize
        }
        return
      }
    }
    
    const params = {
      page: page,
      limit: pageSize
    }
    
    if (filterType.value) {
      params.type = filterType.value
    }
    if (filterStatus.value) {
      params.status = filterStatus.value
    }
    if (dateRange.value && dateRange.value.length === 2) {
      params.startDate = dateRange.value[0]
      params.endDate = dateRange.value[1]
    }

    const response = await getCommissionHistory(params)
    
    if (response.status === 'success') {
      commissionList.value = response.data.list
      commissionPagination.value = {
        ...commissionPagination.value,
        current: response.data.pagination.current,
        total: response.data.pagination.total,
        pageSize: response.data.pagination.pageSize
      }
      
      // 更新缓存
      dataCache.value.commission.set(cacheKey, {
        data: response.data,
        timestamp: Date.now()
      })
    }
  } catch (error) {
    console.error('获取佣金历史失败:', error)
    message.error('获取佣金历史失败')
  } finally {
    commissionLoading.value = false
  }
}

// 刷新佣金数据
const refreshCommissionData = async () => {
  // 清除缓存
  dataCache.value.commission.clear()
  await Promise.all([
    fetchCommissionHistory(commissionPagination.value.current, commissionPagination.value.pageSize)
  ])
}

// 筛选类型变化
const handleFilterChange = () => {
  commissionPagination.value.current = 1
  // 清除缓存
  dataCache.value.commission.clear()
  fetchCommissionHistory(1, commissionPagination.value.pageSize)
}

// 日期范围变化
const handleDateRangeChange = (dates) => {
  if (dates && dates.length === 2) {
    dateRange.value = dates
    commissionPagination.value.current = 1
    // 清除缓存
    dataCache.value.commission.clear()
    fetchCommissionHistory(1, commissionPagination.value.pageSize)
  } else {
    dateRange.value = []
    commissionPagination.value.current = 1
    // 清除缓存
    dataCache.value.commission.clear()
    fetchCommissionHistory(1, commissionPagination.value.pageSize)
  }
}

// 佣金表格翻页处理
const handleCommissionTableChange = (pag, filters, sorter) => {
  commissionPagination.value = pag
  
  // 处理筛选和排序
  if (filters.type) {
    filterType.value = filters.type[0]
  }
  if (filters.status) {
    filterStatus.value = filters.status[0]
  }
  
  fetchCommissionHistory(pag.current, pag.pageSize)
}

// 获取状态颜色
const getStatusColor = (status) => {
  const colorMap = {
    pending: 'orange',
    paid: 'green',
    cancelled: 'red'
  }
  return colorMap[status] || 'default'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    pending: '待发放',
    paid: '已发放',
    cancelled: '已取消'
  }
  return textMap[status] || status
}

// 获取邀请用户状态颜色
const getInviteeStatusColor = (status) => {
  const colorMap = {
    active: 'green',
    expired: 'red'
  }
  return colorMap[status] || 'default'
}

// 获取邀请用户状态文本
const getInviteeStatusText = (status) => {
  const textMap = {
    active: '活跃',
    expired: '已过期'
  }
  return textMap[status] || status
}

// 复制邀请码
const copyCode = async () => {
  if (!inviteCodeData.value) return
  copying.value = true
  try {
    await navigator.clipboard.writeText(inviteCodeData.value.code)
    message.success('邀请码已复制到剪贴板')
  } catch (error) {
    message.error('复制失败，请手动复制')
  } finally {
    copying.value = false
  }
}

// 复制邀请链接
const copyInviteLink = async () => {
  if (!inviteCodeData.value) return
  copying.value = true
  try {
    await navigator.clipboard.writeText(inviteCodeData.value.inviteUrl)
    message.success('邀请链接已复制到剪贴板')
  } catch (error) {
    message.error('复制失败，请手动复制')
  } finally {
    copying.value = false
  }
}

// 分享邀请
const shareInvite = () => {
  if (!inviteCodeData.value) return
  const shareUrl = inviteCodeData.value.inviteUrl
  if (navigator.share) {
    navigator.share({
      title: '邀请您注册',
      text: `点击链接注册，享受丰厚佣金奖励！\n${shareUrl}`,
      url: shareUrl
    })
    message.success('邀请链接已分享')
  } else {
    message.warning('您的浏览器不支持分享功能，请手动复制链接分享。')
  }
}

// 展开/收起邀请链接
const toggleLinkDisplay = () => {
  showFullLink.value = !showFullLink.value
}

// 联系管理员
const contactAdmin = () => {
  Modal.confirm({
    title: '联系管理员',
    content: '您可以通过以下方式联系管理员：\n1. 客服电话：400-xxx-xxxx\n2. 客服QQ：123456789\n3. 邮箱：admin@example.com',
    okText: '我知道了',
    cancelText: '取消'
  })
}

// 邀请表格翻页处理
const handleInviteTableChange = (pag, filters, sorter) => {
  invitePagination.value = pag
  fetchInvitees(pag.current)
}



// 格式化数字
const formatNumber = (num) => {
  if (num === null || num === undefined) return '0'
  return num.toLocaleString()
}

// 格式化金额
const formatMoney = (num) => {
  if (num === null || num === undefined) return '0.00'
  return num.toFixed(2)
}

// 格式化手机号
const formatPhone = (phone) => {
  if (!phone) return '-'
  if (phone.length === 11) {
    return `${phone.substring(0, 3)}****${phone.substring(7)}`
  }
  return phone
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleDateString() + ' ' + date.toLocaleTimeString()
}

// 获取时间差（秒）
const getTimeDiffInSeconds = (date1, date2) => {
  const diffInMs = Math.abs(date1 - date2)
  return Math.floor(diffInMs / 1000)
}

// 获取时间差文本
const getTimeAgo = (dateStr) => {
  const date = new Date(dateStr)
  const now = new Date()
  const diffInSeconds = getTimeDiffInSeconds(now, date)

  if (diffInSeconds < 60) {
    return `${diffInSeconds}秒前`
  } else if (diffInSeconds < 3600) {
    return `${Math.floor(diffInSeconds / 60)}分钟前`
  } else if (diffInSeconds < 86400) {
    return `${Math.floor(diffInSeconds / 3600)}小时前`
  } else {
    return `${Math.floor(diffInSeconds / 86400)}天前`
  }
}

// 显示统计详情
const showStatDetail = (key) => {
  statDetailTitle.value = `详情 - ${key}`
  statDetailData.value = {
    current: inviteStats.value[key] || 0,
    growth: inviteStats.value.inviteGrowth || 0 // 假设佣金增长是基于邀请人数的
  }
  statDetailVisible.value = true
}

// 显示佣金计算器
const showCommissionCalculator = () => {
  calculatorVisible.value = true
  calculatorType.value = 'sell'
  calculatorAmount.value = 0
  calculatorProfit.value = 0
  calculatedCommission.value = '0.00'
}

// 计算佣金
const calculateCommission = () => {
  let result = 0
  if (calculatorType.value === 'sell') {
    if (calculatorProfit.value > 0) {
      result = calculatorProfit.value * (inviteStats.value.commissionRate?.sell || 0.3)
    }
  } else if (calculatorType.value === 'rent') {
    if (calculatorAmount.value > 0) {
      result = calculatorAmount.value * (inviteStats.value.commissionRate?.rent || 0.05)
    }
  }
  calculatedCommission.value = formatMoney(result)
}

// 佣金计算器输入变化
const handleCalculatorInputChange = () => {
  calculateCommission()
}

// 佣金计算器类型变化
const handleCalculatorTypeChange = () => {
  calculatorAmount.value = 0
  calculatorProfit.value = 0
  calculatedCommission.value = '0.00'
}

// 显示佣金规则详情
const showRuleDetail = (type) => {
  message.info(`${type === 'sell' ? '出售账号' : '租赁账号'}佣金规则详情`)
}

// 显示佣金计算规则
const showCommissionRules = () => {
  message.info('佣金计算规则详情')
}

// 查看邀请用户详情
const viewInviteeDetail = (record) => {
  Modal.info({
    title: '邀请用户详情',
    content: `
      <div>
        <p><strong>用户名：</strong>${record.invitee?.username || '-'}</p>
        <p><strong>手机号：</strong>${formatPhone(record.invitee?.phone) || '-'}</p>
        <p><strong>注册时间：</strong>${formatDate(record.registeredAt)}</p>
        <p><strong>产生佣金：</strong>¥${formatMoney(record.commission?.total || 0)}</p>
        <p><strong>佣金笔数：</strong>${record.commission?.count || 0}笔</p>
      </div>
    `,
    okText: '确定'
  })
}

// 发送消息
const sendMessage = (record) => {
  message.info(`向 ${record.invitee?.username} 发送消息功能开发中...`)
}

// 查看佣金详情
const viewCommissionDetail = (record) => {
  Modal.info({
    title: '佣金详情',
    content: `
      <div>
        <p><strong>类型：</strong>${record.type === 'sell' ? '出售佣金' : '租赁佣金'}</p>
        <p><strong>被邀请用户：</strong>${record.invitee?.username || '-'}</p>
        <p><strong>账号编号：</strong>${record.account?.number || '-'}</p>
        <p><strong>订单金额：</strong>¥${formatMoney(record.orderAmount || 0)}</p>
        <p><strong>佣金比例：</strong>${(record.commissionRate * 100).toFixed(1)}%</p>
        <p><strong>佣金金额：</strong>¥${formatMoney(record.commissionAmount || 0)}</p>
        <p><strong>状态：</strong>${getStatusText(record.status)}</p>
        <p><strong>发放时间：</strong>${record.paidAt ? formatDate(record.paidAt) : '-'}</p>
        <p><strong>备注：</strong>${record.remark || '-'}</p>
      </div>
    `,
    okText: '确定'
  })
}

// 重新申请佣金
const reapplyCommission = (record) => {
  Modal.confirm({
    title: '重新申请佣金',
    content: `确定要重新申请这笔佣金吗？\n佣金金额：¥${formatMoney(record.commissionAmount || 0)}`,
    okText: '确定',
    cancelText: '取消',
    onOk: () => {
      message.success('重新申请成功，请等待审核')
    }
  })
}

// 导出佣金数据
const exportCommission = async () => {
  exporting.value = true
  try {
    const params = {
      page: 1,
      limit: commissionPagination.value.total
    }
    
    if (filterType.value) {
      params.type = filterType.value
    }
    if (filterStatus.value) {
      params.status = filterStatus.value
    }
    if (dateRange.value && dateRange.value.length === 2) {
      params.startDate = dateRange.value[0]
      params.endDate = dateRange.value[1]
    }

    const response = await getCommissionHistory(params)
    if (response.status === 'success') {
      const blob = new Blob([JSON.stringify(response.data.list, null, 2)], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `佣金明细_${new Date().toISOString().slice(0, 10)}.json`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
      message.success('佣金明细导出成功！')
    }
  } catch (error) {
    console.error('导出佣金明细失败:', error)
    message.error('导出佣金明细失败')
  } finally {
    exporting.value = false
  }
}

// 监听计算器输入变化
watch([calculatorAmount, calculatorProfit, calculatorType], () => {
  calculateCommission()
})

// 页面加载
onMounted(async () => {
  try {
    await Promise.all([
      fetchInviteStats(),
      fetchMyInviteCode(),
      fetchInvitees(),
      fetchCommissionHistory()
    ])
  } catch (error) {
    console.error('页面初始化失败:', error)
    message.error('页面加载失败，请刷新重试')
  }
})

// 页面卸载时清理缓存
onUnmounted(() => {
  dataCache.value = {
    stats: null,
    inviteCode: null,
    invitees: new Map(),
    commission: new Map()
  }
})

// SEO
definePageMeta({
  title: '邀请中心',
  requiresAuth: true
})
</script>

<style scoped>
.invite-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 16px;
  min-height: 100vh;
}

.page-header {
  text-align: center;
  margin-bottom: 20px;
  animation: fadeInDown 0.8s ease-out;
}

.page-title {
  font-size: 24px;
  font-weight: 700;
  color: #1d2939;
  margin-bottom: 0;
}

.invite-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.tab-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
  animation: fadeIn 0.8s ease-out 0.4s both;
}

/* 统计卡片 */
.stats-section {
  width: 100%;
}

.stats-card {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  padding: 20px;
  background: white;
  border-radius: 12px;
  color: #333;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid #e9ecef;
}

.stat-item {
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  z-index: 1;
  padding: 12px;
  border-radius: 8px;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
}

.stat-item:hover {
  transform: translateY(-3px) scale(1.02);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  background: white;
  border-color: #1890ff;
}

.stat-icon {
  font-size: 24px;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #e6f7ff;
  border-radius: 50%;
  flex-shrink: 0;
  margin: 0 auto 8px;
  transition: all 0.3s ease;
}

.stat-item:hover .stat-icon {
  transform: scale(1.1) rotate(5deg);
  background: #1890ff;
  color: white;
}

.stat-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-number {
  font-size: 24px;
  font-weight: 700;
  margin-bottom: 4px;
  color: #1890ff;
  transition: all 0.3s ease;
}

.stat-item:hover .stat-number {
  transform: scale(1.05);
  color: #096dd9;
}

.stat-label {
  font-size: 12px;
  color: #666;
  font-weight: 500;
  transition: all 0.3s ease;
}

.stat-trend {
  font-size: 10px;
  color: #52c41a;
  display: flex;
  align-items: center;
  gap: 2px;
  margin-top: 4px;
  padding: 2px 6px;
  background: #f6ffed;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.stat-trend span {
  font-size: 12px;
  font-weight: bold;
}

/* 邀请码和邀请用户列表容器 - 左右对齐 */
.invite-sections-container {
  display: grid;
  grid-template-columns: 1fr 2fr;
  gap: 16px;
  width: 100%;
}

/* 邀请码卡片 */
.invite-code-section {
  width: 100%;
}

.invite-card :deep(.ant-card) {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  overflow: hidden;
  border: 1px solid #e9ecef;
}

.invite-card :deep(.ant-card:hover) {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
  transform: translateY(-1px);
}

.invite-card :deep(.ant-card-head) {
  border-bottom: 1px solid #f0f0f0;
  padding: 0 16px;
  min-height: 48px;
  background: #f8f9fa;
}

.invite-card :deep(.ant-card-head-title) {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  padding: 12px 0;
}

.invite-code-content {
  padding: 16px 0;
}

.code-display {
  text-align: center;
  margin-bottom: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 2px dashed #dee2e6;
  transition: all 0.3s ease;
}

.code-display:hover {
  border-color: #1890ff;
  background: #e6f7ff;
  transform: scale(1.01);
}

.code-text {
  font-size: 28px;
  font-weight: 700;
  color: #1890ff;
  font-family: 'Courier New', monospace;
  letter-spacing: 2px;
  margin-bottom: 6px;
  text-shadow: 0 1px 2px rgba(24, 144, 255, 0.2);
  transition: all 0.3s ease;
}

.code-display:hover .code-text {
  transform: scale(1.03);
  color: #096dd9;
}

.code-usage {
  font-size: 12px;
  color: #666;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}

.code-expiry {
  font-size: 10px;
  color: #999;
  margin-top: 2px;
}

.code-actions {
  text-align: center;
  margin-bottom: 16px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  flex-wrap: wrap;
}

.action-buttons .ant-btn {
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  font-size: 12px;
  padding: 4px 12px;
  height: 28px;
}

.action-buttons .ant-btn::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 0;
  height: 0;
  background: rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  transform: translate(-50%, -50%);
  transition: width 0.3s, height 0.3s;
}

.action-buttons .ant-btn:hover::before {
  width: 100%;
  height: 100%;
}

.invite-link {
  background: #f8f9fa;
  padding: 12px;
  border-radius: 6px;
  border: 1px solid #e9ecef;
  transition: all 0.3s ease;
}

.invite-link:hover {
  background: #e9ecef;
  border-color: #dee2e6;
}

.link-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 6px;
}

.link-label {
  font-size: 12px;
  color: #666;
  font-weight: 500;
}

.link-text {
  font-family: 'Courier New', monospace;
  font-size: 12px;
  color: #1890ff;
  word-break: break-all;
  line-height: 1.3;
  white-space: pre-wrap;
  transition: all 0.3s ease;
  max-height: 40px;
  overflow: hidden;
}

.link-text.collapsed {
  max-height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 佣金说明 */
.commission-info {
  width: 100%;
}

.info-card :deep(.ant-card) {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  border: 1px solid #e9ecef;
}

.info-card :deep(.ant-card:hover) {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.commission-rules {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
}

.rule-item {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 6px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.rule-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(24, 144, 255, 0.1), transparent);
  transition: left 0.6s;
}

.rule-item:hover::before {
  left: 100%;
}

.rule-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
  border-color: #1890ff;
  background: #e6f7ff;
}

.rule-icon {
  font-size: 20px;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
  border-radius: 50%;
  flex-shrink: 0;
  margin-bottom: 6px;
  transition: all 0.3s ease;
}

.rule-item:hover .rule-icon {
  transform: scale(1.1) rotate(5deg);
  background: #1890ff;
  color: white;
}

.rule-content {
  flex: 1;
  width: 100%;
}

.rule-title {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  margin-bottom: 3px;
  transition: all 0.3s ease;
}

.rule-item:hover .rule-title {
  color: #1890ff;
}

.rule-desc {
  font-size: 12px;
  color: #666;
  line-height: 1.4;
  margin-bottom: 6px;
  transition: all 0.3s ease;
}

.rule-example {
  font-size: 10px;
  color: #999;
  margin-top: 3px;
  padding: 6px 10px;
  background: rgba(24, 144, 255, 0.1);
  border-radius: 4px;
  border-left: 2px solid #1890ff;
  transition: all 0.3s ease;
}

.rule-item:hover .rule-example {
  background: rgba(24, 144, 255, 0.2);
  color: #1890ff;
}

/* 邀请用户列表 */
.invitees-section {
  width: 100%;
}

.invitees-card :deep(.ant-card) {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  border: 1px solid #e9ecef;
}

.invitees-card :deep(.ant-card:hover) {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 1px;
}

.user-info .username {
  font-weight: 600;
  color: #333;
  margin-bottom: 2px;
  font-size: 13px;
  transition: all 0.3s ease;
}

.user-info .username:hover {
  color: #1890ff;
}

.user-info .phone {
  font-size: 11px;
  color: #666;
}

.commission-info .amount {
  font-weight: 600;
  color: #52c41a;
  margin-bottom: 2px;
  font-size: 13px;
  transition: all 0.3s ease;
}

.commission-info .amount:hover {
  transform: scale(1.03);
}

.commission-info .count {
  font-size: 11px;
  color: #666;
}

/* 佣金明细 */
.commission-history {
  width: 100%;
}

.history-card :deep(.ant-card) {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  border: 1px solid #e9ecef;
}

.history-card :deep(.ant-card:hover) {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.history-card :deep(.ant-card-head) {
  border-bottom: 1px solid #f0f0f0;
  padding: 0 16px;
  min-height: 48px;
  background: #f8f9fa;
}

.history-card :deep(.ant-card-head-title) {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  padding: 12px 0;
}

.filter-controls {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.table-actions {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.account-number {
  font-family: 'Courier New', monospace;
  color: #1890ff;
  font-weight: 600;
  font-size: 12px;
  transition: all 0.3s ease;
}

.account-number:hover {
  color: #096dd9;
  transform: scale(1.03);
}

.account-type {
  font-size: 11px;
  color: #666;
}

.order-amount {
  color: #333;
  font-weight: 600;
  font-size: 12px;
  transition: all 0.3s ease;
}

.order-amount:hover {
  transform: scale(1.03);
}

.commission-rate {
  color: #52c41a;
  font-weight: 600;
  font-size: 12px;
  transition: all 0.3s ease;
}

.commission-rate:hover {
  transform: scale(1.03);
}

.commission-amount {
  color: #ff4d4f;
  font-weight: 700;
  font-size: 14px;
  transition: all 0.3s ease;
}

.commission-amount:hover {
  transform: scale(1.03);
}

.remark {
  color: #666;
  font-size: 11px;
  transition: all 0.3s ease;
}

.remark:hover {
  color: #333;
}

.date-info {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  font-size: 11px;
  color: #999;
}

.date-info .date {
  margin-bottom: 2px;
  transition: all 0.3s ease;
}

.date-info .date:hover {
  color: #666;
}

.time-ago {
  font-size: 9px;
  opacity: 0.8;
}

/* 佣金规则说明 */
.commission-rules-section {
  width: 100%;
}

.rules-card :deep(.ant-card) {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  border: 1px solid #e9ecef;
}

.rules-card :deep(.ant-card:hover) {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.rules-content {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 16px;
}

.rule-section {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.rule-section::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(24, 144, 255, 0.1), transparent);
  transition: left 0.6s;
}

.rule-section:hover::before {
  left: 100%;
}

.rule-section:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
  border-color: #1890ff;
  background: #e6f7ff;
}

.rule-section .rule-title {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 12px;
  font-size: 14px;
  font-weight: 600;
  color: #333;
  transition: all 0.3s ease;
}

.rule-section:hover .rule-title {
  color: #1890ff;
}

.rule-section .rule-icon {
  font-size: 18px;
  transition: all 0.3s ease;
}

.rule-section:hover .rule-icon {
  transform: scale(1.1) rotate(5deg);
}

.rule-formula {
  font-family: 'Courier New', monospace;
  font-size: 14px;
  font-weight: 700;
  color: #1890ff;
  background: white;
  padding: 10px 12px;
  border-radius: 6px;
  border: 2px solid #e6f7ff;
  margin-bottom: 10px;
  transition: all 0.3s ease;
}

.rule-section:hover .rule-formula {
  border-color: #1890ff;
  background: #f0f8ff;
  transform: scale(1.01);
}

.rule-detail .rule-desc {
  font-size: 12px;
  color: #666;
  line-height: 1.5;
  margin-bottom: 10px;
  transition: all 0.3s ease;
}

.rule-section:hover .rule-desc {
  color: #333;
}

.rule-list {
  margin: 0;
  padding-left: 16px;
}

.rule-list li {
  font-size: 12px;
  color: #666;
  line-height: 1.5;
  margin-bottom: 6px;
  transition: all 0.3s ease;
  position: relative;
}

.rule-list li::before {
  content: '•';
  color: #1890ff;
  font-weight: bold;
  position: absolute;
  left: -12px;
  transition: all 0.3s ease;
}

.rule-section:hover .rule-list li {
  color: #333;
}

.rule-section:hover .rule-list li::before {
  transform: scale(1.2);
}

.rule-list li:last-child {
  margin-bottom: 0;
}

/* 统计详情弹窗 */
.stat-detail-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16px;
}

.stat-chart {
  width: 100%;
  height: 160px;
  background: #f8f9fa;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 16px;
  border: 2px dashed #dee2e6;
  transition: all 0.3s ease;
}

.stat-chart:hover {
  border-color: #1890ff;
  background: #e6f7ff;
}

.chart-placeholder {
  font-size: 14px;
  color: #999;
  transition: all 0.3s ease;
}

.stat-chart:hover .chart-placeholder {
  color: #1890ff;
}

.stat-summary {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  width: 100%;
}

.summary-item {
  display: flex;
  align-items: baseline;
  gap: 6px;
  padding: 10px 12px;
  background: #f8f9fa;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.summary-item:hover {
  background: #e9ecef;
  transform: translateX(3px);
}

.summary-item .label {
  font-size: 12px;
  color: #666;
  font-weight: 500;
}

.summary-item .value {
  font-size: 18px;
  font-weight: 700;
  color: #333;
  transition: all 0.3s ease;
}

.summary-item .value.positive {
  color: #52c41a;
}

.summary-item .value.negative {
  color: #ff4d4f;
}

/* 佣金计算器弹窗 */
.calculator-content {
  padding: 16px;
}

.commission-result {
  font-size: 20px;
  font-weight: 700;
  color: #ff4d4f;
  text-align: center;
  margin-top: 8px;
  padding: 12px;
  background: #fff1f0;
  border-radius: 6px;
  border: 2px solid #ffccc7;
  transition: all 0.3s ease;
}

.commission-result:hover {
  transform: scale(1.01);
  box-shadow: 0 3px 8px rgba(255, 77, 79, 0.2);
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 30px 16px;
  color: #999;
  animation: fadeIn 0.8s ease-out;
}

.empty-icon {
  font-size: 36px;
  margin-bottom: 12px;
  opacity: 0.6;
  transition: all 0.3s ease;
}

.empty-state:hover .empty-icon {
  opacity: 1;
  transform: scale(1.05);
}

.empty-state p {
  margin-bottom: 16px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.empty-state:hover p {
  color: #666;
}

/* 无权限提示样式 */
.no-permission {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 16px;
  text-align: center;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
  animation: fadeIn 0.8s ease-out;
}

.permission-icon {
  font-size: 36px;
  margin-bottom: 12px;
  opacity: 0.6;
  transition: all 0.3s ease;
}

.no-permission:hover .permission-icon {
  opacity: 1;
  transform: scale(1.05);
}

.permission-text h3 {
  color: #333;
  margin-bottom: 6px;
  font-size: 16px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.no-permission:hover .permission-text h3 {
  color: #1890ff;
}

.permission-text p {
  color: #666;
  margin: 0 0 12px 0;
  font-size: 12px;
  line-height: 1.4;
  transition: all 0.3s ease;
}

.no-permission:hover .permission-text p {
  color: #333;
}

/* 动画定义 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes fadeInDown {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .rules-content {
    grid-template-columns: 1fr;
  }
  
  .stats-card {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
    padding: 16px;
  }
  
  .invite-sections-container {
    grid-template-columns: 1fr;
    gap: 12px;
  }
}

@media (max-width: 768px) {
  .invite-page {
    padding: 12px;
  }

  .page-title {
    font-size: 20px;
  }

  .stats-card {
    grid-template-columns: 1fr;
    padding: 12px;
    gap: 12px;
  }

  .stat-card {
    padding: 12px;
  }

  .stat-card .stat-number {
    font-size: 18px;
  }

  .stat-icon {
    font-size: 20px;
    width: 36px;
    height: 36px;
  }

  .stat-number {
    font-size: 20px;
  }

  .code-text {
    font-size: 20px;
    letter-spacing: 1px;
  }

  .action-buttons {
    flex-direction: column;
    align-items: center;
  }

  .commission-rules {
    grid-template-columns: 1fr;
  }

  .filter-controls {
    flex-direction: column;
    gap: 6px;
  }

  .table-actions {
    flex-direction: column;
    gap: 6px;
  }

  .rule-section {
    padding: 12px;
  }
}

@media (max-width: 480px) {
  .invite-page {
    padding: 8px;
  }

  .page-title {
    font-size: 18px;
  }

  .stats-card {
    padding: 12px;
  }

  .stat-card {
    padding: 8px;
  }

  .code-text {
    font-size: 18px;
    letter-spacing: 1px;
  }

  .action-buttons .ant-btn {
    width: 100%;
  }

  .filter-controls .ant-select,
  .filter-controls .ant-picker {
    width: 100% !important;
  }
}
</style>